package com.example.x50.untils;

public class int2hex {
	public static void main(String[] args) {

		System.out.println(decimalToHex(255,4));
	}
	//将0~15的十进制数转换成0~F的十六进制数
	public static char toHexChar(int hexValue) {
		if(hexValue <= 9 && hexValue >= 0)
			return (char)(hexValue + '0');
		else
			return (char)(hexValue - 10 + 'A');
	}
	public static String decimalToHex(int decimal,int length) {
		String hex = "";
		int i=0;
//		if(decimal==0) return "00";
		while(decimal != 0) {
			i++;
			length--;
			int hexValue = decimal % 16;
			hex = toHexChar(hexValue) + hex;
			decimal = decimal / 16;

		}
		for (;length>0;length--){
			hex="0"+hex;
		}
		//获得偶数为的16进制字符串
//		if(i%2!=0) hex="0"+hex;

		return  hex;
	}
}

